
'use strict'

import {CITY_DATA} from '../util/distpicker'
import {extend} from '../../../sdk/extend'
import { requestApi } from '../../../api'
import { formatImage } from '../../../utils/formatImage'

const app = getApp()
const postReg = /^\d{6}$/
const mobileReg = /^(13|15|17|18|14|19|16)[0-9]{9}$/
const idReg = /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressList: [],  // 地址列表信息
    index: '',
    refer: '',
    identifyType: '0', // 是否需要补充身份信息 0:不需要 1:号码&照片 2:仅号码
    data: {},    // 地址信息
    provinces: [],
    citys: [],
    districts: [],
    condition: false,
    permanent: '',
    idNumber: '', // 身份证号码
    front: {},   // 身份证正面
    back: {} ,    // 身份证反面
    hidden: true,  // 图片上传提示  
    isShow: false, // 是否显示身份证信息
    isDefault: false,  // switch是否选中
    isDefaultShow: false,  // switch是否show 避免选中的动画
    timeDifference: 0,
    isIdentifyFilled: false, // 根据identifyType条件，判断身份证号码/号码是否已填写
    region: [0, 0, 0],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.refer = options.refer || ''

    if (options.identifyType) {
      this.setData({
        identifyType: options.identifyType,
      })
    }
    
    wx.getStorage({
      key: 'addressList',
      success: res => {
        this.setData({
          addressList: res.data
        })
        
        if (options.index !== undefined && options.index !== '') {
          const identifyType = this.data.identifyType
          let index = options.index
          let data = res.data[index]

          // 根据身份证号码/照片，确定是否需要显示“身份信息“模块
          if (identifyType !== '0') {
            const isShow = true
            let isIdentifyFilled = false

            if (identifyType === '2' && data.id_number) {
              isIdentifyFilled = true
            } else if (identifyType === '1' && data.id_number && data.id_images && data.id_images.front && data.id_images.back) {
              isIdentifyFilled = true
            }

            this.setData({
              isShow,
              isIdentifyFilled,
            })
          }

          // 会有部分省份数据上报不全（基本是脏数据），如：“北京市”上报时直接写为“北京”
          if (data.province && data.province.length === 2) {
            for (var i = 0, len = CITY_DATA.length; i < len; i++) {
              const provinceName = CITY_DATA[i].name

              // 更正“省份”
              if (provinceName.indexOf(data.province) === 0) {
                data.province = provinceName
                this.data.province = provinceName
                break
              }
            }
          }
          
          this.setData({
            index,
            data,
            isDefault: data.is_default == 1 ? true : false,
            permanent: data.province + ' ' + data.city + ' ' + data.district,
            idNumber: data.id_number || '',
            'front.path': data.id_images && data.id_images.front && data.id_images.front.path ? formatImage.cdnImage(data.id_images.front.path) : '',
            'back.path': data.id_images && data.id_images.back && data.id_images.back.path ? formatImage.cdnImage(data.id_images.back.path) : ''    
          })
        }

        // 初始化
        this.setData({
          isDefaultShow: true,
        });
        // 初始省市区数据
        var cityData = CITY_DATA;

        const provinces = [];
        const citys = [];
        const districts = [];
        // 默认省份和城市的下标索引值为0
        let provinceIndex = 0;
        let cityIndex = 0;
        let districtIndex = 0;
        let province = this.data.data.province ? this.data.data.province : '北京市'
        let city = this.data.data.city ? this.data.data.city : '北京市'
        let district = this.data.data.district ? this.data.data.district : '东城区'

        for (let i = 0; i < cityData.length; i++) {
          provinces.push(cityData[i].name);
        }
        
        provinceIndex = provinces.indexOf(province)

        if (cityData[provinceIndex].sub && cityData[provinceIndex].sub.length) {
          for (let i = 0; i < cityData[provinceIndex].sub.length; i++) {
            citys.push(cityData[provinceIndex].sub[i].name)
          }

          cityIndex = citys.indexOf(city)

          if (cityData[provinceIndex].sub[cityIndex].sub && cityData[provinceIndex].sub[cityIndex].sub.length) {
            for (let i = 0; i < cityData[provinceIndex].sub[cityIndex].sub.length; i++) {
              districts.push(cityData[provinceIndex].sub[cityIndex].sub[i].name)
            }

            districtIndex = districts.indexOf(district)
          }
        }

        this.setData({
          provinces: provinces,
          citys: citys,
          districts: districts,
          value: [provinceIndex, cityIndex, districtIndex],
          values: [provinceIndex, cityIndex, 0],
        })
      },
    })
  },
 
  // 所在地区改变事件
  choosearea: function () {
    this.setData({
      condition: ! this.data.condition
    })
  },

  bindLocationChange: function (e) {
    var val = e.detail.value;
    var province = val[0];
    var city = val[1];
    var district = val[2];

    this.setData({
      permanent: province + ' ' + city + ' ' + district,
      'data.province': province,
      'data.city': city,
      'data.district': district,
    })
  },

  bindLocationSure: function () {
    let province = !this.data.data.province ? '北京市' : this.data.data.province
    let city = !this.data.data.city ? '北京市' : this.data.data.city
    let district = !this.data.data.district ? '东城区' : this.data.data.district
    this.setData({
      permanent: province + ' ' + city + ' ' + district,
      'data.province': province,
      'data.city': city,
      'data.district': district,
      condition: !this.data.condition
    })
  },

  // 身份证信息折叠
  cardFold: function () {
    this.setData({
      isShow: !this.data.isShow
    })
  },

  // 身份证信息输入
  bindIdNumberInput(e) {
    this.setData({
      idNumber: e.detail.value.trim(),
    })
  },

  // 身份证信息失去焦点
  bindIdNumberBlur() {
    this.handleIdentifyFilledStatus()
  },

  // 验证“身份证信息”模块填写状态
  handleIdentifyFilledStatus() {
    let isIdentifyFilled = this.data.isIdentifyFilled

    if (this.data.idNumber.trim() === '' || !this.data.front.path || !this.data.back.path) {
      isIdentifyFilled = false
    } else {
      isIdentifyFilled = true
    }

    this.setData({
      isIdentifyFilled,
    })
  },

  // image 
  chooseImageTap: function (e) {
    let flag = e.currentTarget.dataset.flag  //身份证的正front 、反back
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: (res) => {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            this.chooseWxImage('album', flag)
          } else if (res.tapIndex == 1) {
            this.chooseWxImage('camera', flag)
          }
        }
      }
    })
  },

  chooseWxImage: function (type, flag) {
    let that = this

    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: (res) => {
        var filePath = res.tempFilePaths[0]

        this.setData({
          hidden: false
        })
        
        wx.getStorage({
          key: 'timeDifference',
          success: (response) => {
            this.setData({
              timeDifference: response.data,
            })
          }
        })

        that.uploadFile(res.tempFiles, flag)
      }
    })
  },

  imageLoad(e) {
    const flag = e.target.dataset.flag
    const width = e.detail.width
    const height = e.detail.height

    // 修正图片的宽高
    if (flag === 'front') {
      this.setData({
        'data.id_images.front.width': width,
        'data.id_images.front.height': height,
        'front.width': width,
        'front.height': height,
      })
    } else if (flag === 'back') {
      this.setData({
        'data.id_images.back.width': width,
        'data.id_images.back.height': height,
        'back.width': width,
        'back.height': height,
      })
    }    
  },

  imageError(e) {
    console.log('imageError', e)
  },

  uploadFile: function (tempFiles, flag) {
    const tempFilePaths = tempFiles[0].path
    const tempFileSize = tempFiles[0].size
    const tempArr = tempFilePaths.split('.')
    const tempFileType = tempArr[tempArr.length - 1]
    const date = new Date()
    const timestamp = Math.floor(new Date() / 1000) + this.data.timeDifference // 时间戳 秒
    const time = `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`
    let that = this

    let authPath = 'mars' + `/${time}`

    const params = {
      auth_path: authPath,
      file_size: tempFileSize,
      timestamp: timestamp,
      file_type: tempFileType,
    }

    app.request({
      url: requestApi.webOssAuthUrl,
      methods: 'GET',
      data: params
    }, res => {
      let ossKey = res.original.oss_key

      wx.uploadFile({
        url: ossKey.host,
        filePath: tempFilePaths,
        name: 'file',
        formData: {
          name: tempFilePaths,
          key: ossKey.auth_path,
          OSSAccessKeyId: ossKey.accessid,
          policy: ossKey.policy,
          signature: ossKey.signature,
          success_action_status: '200',
        },
        success() {
          that.setData({
		        hidden: true
	        })

          let front = {
            path: `/${ossKey.auth_path}`,
            width: 100,
            height: 100,
          }

          let frontFull = {
            path: formatImage.cdnImage(front.path),
            width: 100,
            height: 100,
          }

	        // 将图片显示
	        if (flag == 'front') {
            that.setData({
              'data.id_images.front': front,
              front: frontFull
		        })
	        } else {
            that.setData({
              'data.id_images.back': front,
              back: frontFull
		        })
          }
          
          that.handleIdentifyFilledStatus()
        },
        fail(error) {
          wx.showModal({
            title: '提示',
            content: error,
            showCancel: false
          })
        }
      })

    }, (error) => {
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false
      })
      this.setData({
        hidden: true
      })
    })
  },

  // save
  formSubmit: function (e) {
    // identifyType 商品是否需要补充身份信息 0:不需要 1:号码&照片 2:仅号码
    const identifyType = this.data.identifyType
    let msg = ''

    if (e.detail.value.recipeint.trim() === '') {
      msg = '请填写收货人姓名'
    } else if (e.detail.value.mobilephone.trim() === '' || !mobileReg.test(e.detail.value.mobilephone)) {
      msg = '请填写收货人手机号'
    } else if (this.data.permanent.trim() === '') {
      msg = '请填写所在地区'
    } else if (e.detail.value.address.trim() === '') {
      msg = '请填写详细收货地址'
    } else if (e.detail.value.postcode.trim() !== '' && !postReg.test(e.detail.value.postcode.trim())) {
      msg = '邮编须是六位数字'
    } else if (identifyType !== '0') {
      // 当isShow为false时，身份证信息模块是隐藏的，无法获取身份证号码、照片字段
      // 即，无法获取 e.detail.value.id_number 字段
      if (!this.data.idNumber) {
        msg = '请输入收货人对应的身份证号码'
      } else if (!idReg.test(this.data.idNumber)) {
        msg = '身份证号码格式错误'
      } else if (identifyType === '1' && (!this.data.front.path || !this.data.back.path)) {
        msg = '请上传身份证照片'
      }
    }
    
    if (msg) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: msg,
      })

      return
    }

    // 校验用户身份证信息
    if (identifyType !== '0') {
      const identifyData = {
        identity_card_name: e.detail.value.recipeint.trim(),
        identity_card_no: this.data.idNumber,
      }

      // 还需要校验身份证信息
      if (identifyType === '1') {
        identifyData.identity_card_url = this.data.data.id_images.front.path
      }

      if (this.saveFlag) return

      this.saveFlag = true

      app.request({
        url: requestApi.verifyUserIdentityInfo,
        data: identifyData,
        method: 'POST',
      }, data => {
        // 传递身份证校验信息
        this.data.addressList[this.data.index].identifyType = '0'
        this.saveFlag = false
        this.saveAddress(e.detail)
      }, error => {
        // 校验身份证信息失败
        wx.showModal({
          title: '提示',
          content: error,
          showCancel: false
        })

        this.saveFlag = false
      })

      return
    }

    this.saveAddress(e.detail)
  },

  // 保存地址信息
  saveAddress(eventDetail) {
    if (this.saveFlag) return

    this.saveFlag = true

    let param = this.data.data

    param = extend({}, param, eventDetail.value)

    // 转换原后端逻辑
    param = this.submit_handle(param, 1, param.id)

    let changePrams = JSON.parse(JSON.stringify(param))

    // 区分地址修改状态
    if (this.data.index !== '') {
      changePrams = this.change_handle(changePrams)
    }
   
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2] 
    let prevTwoPage = pages[pages.length - 3] 

    // 请求接口
    app.request({
      url: requestApi.addressSaveUrl,
      data: param,
      method: 'POST'
    }, data => {
      let list = this.data.addressList
      let idNumList = []

      // list里只有一个为默认值
      if (eventDetail.value.is_default == true && list.length) {  
        for (let i = 0, len = list.length; i < len ; i++ ) {
          list[i]['is_default'] = 0
        }
      }

      if (this.data.index != '') {  // 编辑
        let index = this.data.index
        list[index] = param;  
      } else {       // 新建
        param = extend({}, param, {id: data.original.addr_id})
        list.push(param)
      }

      if (list.length) {
        for (let i = 0, len = list.length; i < len; i++) {
          list[i]['id_number_cn'] = list[i]['id_number'] ?
            list[i]['id_number'].substring(0, 4) + '******' + list[i]['id_number'].substr(-6) : ''
          idNumList[i] = list[i]['id_number'] ?
            list[i]['id_number'].substring(0, 4) + '******' + list[i]['id_number'].substr(-6) : ''
        }
      }

      // 从地址列表页、下单确认页跳转过来 this.data.refer === 'order', 将addressData/addressList数据压入前一个页面
      if (prevPage) {
        prevPage.setData({
          idNumList,
          addressData: list[this.data.index],
          addressIndex: this.data.index,
          addressList: list,
        })
      }
      
      // 前两页重置数据
      if (eventDetail.value.is_default == true ) {
        let address = this.data.permanent + param.address

        if (prevTwoPage) {
          prevTwoPage.setData({
            address: address,
            addressData: list[this.data.index],
          })
        }
      }

      // 同步存储storage
      try {
        wx.setStorageSync('addressList', list)
      } catch (e) {
        // 
      }
      
      wx.navigateBack()
    }, error => {
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false
      })
    }, () => {
      this.saveFlag = false
    })
  },

  submit_handle: function (param, recode_status, id) {
    if (recode_status) {
      param.record_status = recode_status
    }
    if (id) {
      param.addr_id = param.id || ''
    }
   
    param.recipeint = param.recipeint.trim() || ''
    param.mobilephone = param.mobilephone.trim() || ''
    param.province = param.province || ''
    param.city = param.city || ''
    param.district = param.district || ''
    param.address = param.address.trim() || ''
    param.postcode = param.postcode.trim() || ''
    param.id_number = param.id_number.trim() || ''
    param.id_images = param.id_images || {}
    param.is_default = param.is_default ? 1 : 0
    
    return param
  },

  change_handle: function (param) {
    let originalAddress = this.data.addressList[this.data.index]

    if (param.recipeint === originalAddress.recipeint && param.id_number === originalAddress.id_number && originalAddress.id_images && param.id_images.front && param.id_images.front.path === originalAddress.id_images.front.path && param.id_images.back && param.id_images.back.path === originalAddress.id_images.back.path) {
      delete param.id_images
      delete param.recipeint
      delete param.id_number
    }

    return param
  },

  // delete
  delete: function (e) {
    let data = {
      'record_status': 0,
      'addr_id' : this.data.data.id
    }
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2] 

    wx.showModal({
      title: '提示',
      content: '确认进行删除该地址吗？',
      success: (res)=> {
        if (res.confirm) {
          app.request({
            url: requestApi.addressSaveUrl,
            data: data,
            method: 'POST'
          }, (data) => {
            let addressList = this.data.addressList
            let index = this.data.index
            addressList.splice(index, 1)
            prevPage.setData({
              addressList: addressList
            })
            wx.setStorage({
              key: 'addressList',
              data: addressList,
            }) 
            wx.navigateBack()
          },(error)=> {
            wx.showModal({
              title: '提示',
              content: error,
              showCancel: false
            })
          })
        } else if (res.cancel) {
        }
      }
    })
  },
})